package cn.learn.server;

import cn.learn.server.jute.InputArchive;
import cn.learn.server.jute.OutputArchive;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class DataNode implements Record {
    byte[] data;
    Long acl;
    public StatPersisted stat;

    private Set<String> children = null;

    private static final Set<String> EMPTY_SET = Collections.emptySet();

    public DataNode(){}

    public DataNode(byte[] data, Long acl, StatPersisted stat) {
        this.data = data;
        this.acl = acl;
        this.stat = stat;
    }

    public synchronized boolean addChild(String child) {
        if (children == null) {
            children = new HashSet<String>(8);
        }
        return children.add(child);
    }

    public synchronized Set<String> getChildren() {
        if (children == null) {
            return EMPTY_SET;
        }

        return Collections.unmodifiableSet(children);
    }

    public synchronized byte[] getData() {
        return data;
    }

    @Override
    public synchronized void serialize(OutputArchive archive, String tag) throws IOException {
        archive.startRecord(this, "node");
        archive.writeBuffer(data, "data");
        archive.writeLong(acl, "acl");
        stat.serialize(archive, "statpersisted");
        archive.endRecord(this, "node");
    }

    @Override
    public void deserialize(InputArchive ia, String fileheader) throws IOException {

    }
}
